package easy;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * 给定一个数组 nums，编写一个函数将所有 0 移动到数组的末尾，同时保持非零元素的相对顺序。
 * 请注意 ，必须在不复制数组的情况下原地对数组进行操作。
 * 示例 1:
 * 输入: nums = [0,1,0,3,12]
 * 输出: [1,3,12,0,0]
 * 示例 2:
 * 输入: nums = [0]
 * 输出: [0]
 */
public class leetcode283 {

    public static void main(String[] args) {
        int[] nums = {0, 1, 0, 3, 12};
        moveZeroes4(nums);
        System.out.println(Arrays.toString(nums));
    }

    public static void moveZeroes1(int[] nums) {
        int zero = 0, cur = 0, count = 0;
        while (cur < nums.length) {
            if (nums[cur] == 0) {
                zero = count != 0 ? zero : cur;
                count++;
            } else if (count > 0) {
                int temp = nums[zero];
                nums[zero] = nums[cur];
                nums[cur] = temp;
                cur--;
                if (count-- > 1) {
                    zero++;
                }
            }
            cur++;
        }
    }

    private static void moveZeroes2(int[] nums) {
        int[] arr = new int[nums.length];
        int l = 0, r = 0;
        while (l < arr.length && r < nums.length) {
            if (nums[r] != 0) {
                arr[l++] = nums[r++];
            } else {
                r++;
            }
        }
        while (l < arr.length) {
            arr[l++] = 0;
        }
        for (int i = 0; i < arr.length; i++) {
            nums[i] = arr[i];
        }
    }

    private static void moveZeroes3(int[] nums) {
        ArrayList<Integer> list = new ArrayList<>();
        for (int i : nums) {
            list.add(i);
        }
        int index = 0;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i) != 0) {
                nums[index++] = list.remove(i);
                i--;
            }
        }
        for (Integer num : list) {
            nums[index++] = num;
        }
    }

    public static void moveZeroes4(int[] nums) {
        if (nums == null) {
            return;
        }
        //两个指针i和j
        int j = 0;
        for (int i = 0; i < nums.length; i++) {
            //当前元素!=0，就把其交换到左边，等于0的交换到右边
            if (nums[i] != 0) {
                int tmp = nums[i];
                nums[i] = nums[j];
                nums[j++] = tmp;
            }
        }
    }
}
